$(function() {
	MAP = {} // global var
	var globalData = {};
	var LoadBreadcrumb = function(path) {
		var data = MAP.breadcrumb;
		path = path || [];
		path.shift(); // shift out root
		var $bread = $("ol.breadcrumb");
		$bread.find("li").remove();
		var $li = $("<li><a href='#'>HOME</a></li>");
		$bread.append($li);
		for (var i = 0; i < path.length; i++) {
			if (i === path.length - 1) {
				$li = $("<li>" + path[i] + "</li>");
			} else {
				$li = $("<li><a href=#>" + path[i] + "</a></li>");
			}
			$bread.append($li);
			if (data !== undefined) {
				data = data.children[path[i]];
			}
		}
		var $nav = $("#sidenav");
		$nav.find("a").remove();
		if (data !== undefined) {
			for (var key in data.children) {
				var $li = $("<a> " + key + "</a>").attr("href", "#");
				$li.addClass("list-group-item");
				$li.attr("for", "tree").addClass("glyphicon glyphicon-tree-conifer");
				$nav.append($li);
			}
			for (var i = 0; i < data.values.length; i++) {
				var key = data.values[i];
				var $li = $("<a> " + key + "</a>");
				$li.attr("for", "leaf").attr("href", "#");
				$li.addClass("list-group-item");
				$li.addClass("glyphicon glyphicon-leaf");
				$nav.append($li);
			}
		}
	}

	var $bread = $("ol.breadcrumb");
	var ReadPath = function() {
		var path = [];
		$bread.find("li:not(.active)").each(function() {
			var name = $(this).text();
			path.push(name);
		});
		path.shift(); // shift out root
		return path;
	}

	$.get("api/v1/breadcrumb", {},
	function(r, textStatus) {
		MAP.breadcrumb = r.data;
		LoadBreadcrumb();
	},
	"json");

	LoadChart = function($container, path) {
		var pathName = path.join('/');
		$.get("api/v1/records", {
			"path": pathName
		},
		function(r, statusText) {
			var raw = r.data,
			i, data = [];
			var lastTime = 0;
			for (i = 0; i < raw.length; i++) {
				var x = raw[i][0] / 1000000;
				var y = parseInt(raw[i][1]);
				lastTime = Math.max(x, lastTime);
				data.push([x, y]);
			}
			//var time = Highcharts.dateFormat("%Y/%m/%d %H:%M:%S", lastTime);
			var series = LoadHighStock($container, pathName, data);
			MAP[pathName]['series'] = series;
			MAP[pathName]['last_time'] = lastTime;
		},
		"json");
	}
	// side nav live click
	var $chartBox = $("#chart-container")
	$(document).on("click", "#sidenav>a", function() {
		$this = $(this);
		var t = $this.attr("for");
		var text = $.trim($this.text());
		var index = $this.index();
		path = ReadPath();
		path.push(text);
		if (t === "tree") {
			path.unshift("HOME");
			LoadBreadcrumb(path);
			if (MAP.path_list !== undefined) {
				MAP.path_list.splice($.inArray(path, MAP.path_list), 1);
			}
		} else {
			var pathName = path.join('/');
			$this.toggleClass("active");
			if ($this.hasClass("active")) {
				var text = "loading <b>" + pathName + "</b> ...";
				$container = $("<div>" + text + "</b></div>").height("280px").attr("for", index);
				$chartBox.append($container);
				LoadChart($container, path);
			} else {
				$chartBox.find("div[for=" + index + "]").remove();
			}
			// global MAP for auto refresh
			MAP[pathName] = {}
			MAP.path_list = MAP.path_list || [];
			MAP.path_list.push(path);
		}
	});
	// breadcrumb live click
	$(document).on("click", "ol.breadcrumb>li", function() {
		var path = [$(this).text()];
		$(this).prevAll().each(function() {
			path.unshift($(this).text());
		});
		LoadBreadcrumb(path);
		$chartBox.empty();
	});

	$("div.make-switch").on("switch-change", function(e, data) {
		// auto refresh
		var open = data.value;
		if (open) {
			var id = setInterval(function() {
				UpdateAllStock();
			},
			1000);
			MAP["interval_id"] = id;
		} else {
			var id = MAP["interval_id"];
			clearInterval(id);
		}
	});

	UpdateAllStock = function() {
		var pathList = MAP.path_list || [];
		for (var i = 0; i < pathList.length; i++) {
			UpdateHighStock(pathList[i]);
		}
	}

	UpdateHighStock = function(path) {
		var pathName = path.join('/');
		var ST = MAP[pathName];
		if (ST.running === true) {
			return;
		}
		ST.running = true;
		// in case of ajax error
		var timeoutId = setInterval(function() {
			ST.running = false;
		},
		2000);

		var lastTime = ST.last_time;
		//var time = Highcharts.dateFormat("%Y/%m/%d %H:%M:%S", lastTime);
		if (ST.last_time === undefined) {
			return;
		}
		$.get("api/v1/records", {
			"path": pathName,
			"start": lastTime * 1000000,
		},
		function(r, statusText) {
			var series = MAP[pathName].series;
			var raw = r.data;
			var lastTime = ST.last_time;
			for (var i = 0; i < raw.length; i++) {
				var x = raw[i][0] / 1000000;
				var y = parseInt(raw[i][1]);
				lastTime = Math.max(x, lastTime);
				series && series.addPoint([x, y], true, false);
			}
			ST.last_time = lastTime;
			clearInterval(timeoutId);
			ST.running = false; // defer close running
		},
		"json");

	}
}); // end of jQuery

